<template>
  <div class="dashboard-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="card-header">
            <div class="title">总用户数</div>
            <i class="el-icon-user"></i>
          </div>
          <div class="card-body">
            <div class="number">{{ stats.totalUsers }}</div>
            <div class="growth" :class="{ 'up': stats.userGrowthRate >= 0, 'down': stats.userGrowthRate < 0 }">
              <i :class="stats.userGrowthRate >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
              {{ formatGrowthRate(stats.userGrowthRate) }}% 较上月
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="card-header">
            <div class="title">总订单数</div>
            <i class="el-icon-s-order"></i>
          </div>
          <div class="card-body">
            <div class="number">{{ stats.totalOrders }}</div>
            <div class="growth" :class="{ 'up': stats.orderGrowthRate >= 0, 'down': stats.orderGrowthRate < 0 }">
              <i :class="stats.orderGrowthRate >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
              {{ formatGrowthRate(stats.orderGrowthRate) }}% 较上月
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="card-header">
            <div class="title">总销售额</div>
            <i class="el-icon-money"></i>
          </div>
          <div class="card-body">
            <div class="number">¥{{ formatMoney(stats.totalSales) }}</div>
            <div class="growth" :class="{ 'up': stats.salesGrowthRate >= 0, 'down': stats.salesGrowthRate < 0 }">
              <i :class="stats.salesGrowthRate >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
              {{ formatGrowthRate(stats.salesGrowthRate) }}% 较上月
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="card-header">
            <div class="title">预约数</div>
            <i class="el-icon-date"></i>
          </div>
          <div class="card-body">
            <div class="number">{{ stats.totalAppointments }}</div>
            <div class="growth" :class="{ 'up': stats.appointmentGrowthRate >= 0, 'down': stats.appointmentGrowthRate < 0 }">
              <i :class="stats.appointmentGrowthRate >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
              {{ formatGrowthRate(stats.appointmentGrowthRate) }}% 较上月
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="16">
        <el-card class="chart-card">
          <div slot="header">
            <span>销售趋势</span>
          </div>
          <div ref="salesChart" class="chart"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="chart-card">
          <div slot="header">
            <span>商品类别占比</span>
          </div>
          <div ref="categoryChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最新订单 -->
    <el-card class="latest-orders">
      <div slot="header">
        <span>最新订单</span>
      </div>
      <el-table :data="latestOrders" style="width: 100%">
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="totalAmount" label="金额" width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getOrderStatusType(scope.row.status)">
              {{ getOrderStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
      </el-table>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getDashboardStats, getLatestOrders } from '@/api/admin'

export default {
  name: 'AdminDashboard',
  
  data() {
    return {
      stats: {
        totalUsers: 0,
        totalOrders: 0,
        totalSales: 0,
        totalAppointments: 0,
        userGrowthRate: 0,
        orderGrowthRate: 0,
        salesGrowthRate: 0,
        appointmentGrowthRate: 0
      },
      latestOrders: [],
      salesChart: null,
      categoryChart: null
    }
  },

  mounted() {
    this.fetchDashboardData()
    this.fetchLatestOrders()
    this.initCharts()
    
    // 监听窗口大小变化，重新调整图表大小
    window.addEventListener('resize', this.resizeCharts)
  },

  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts)
    if (this.salesChart) {
      this.salesChart.dispose()
    }
    if (this.categoryChart) {
      this.categoryChart.dispose()
    }
  },

  methods: {
    async fetchDashboardData() {
      try {
        const response = await getDashboardStats()
        if (response.code === 200 && response.data) {
          this.stats = response.data
          
          // 确保总预约数有值
          if (this.stats.totalAppointments === null || this.stats.totalAppointments === undefined) {
            this.stats.totalAppointments = 0
          }
          
          this.updateCharts(response.data)
        } else {
          console.error('获取仪表盘数据异常:', response)
        }
      } catch (error) {
        console.error('获取仪表盘数据失败:', error)
      }
    },

    async fetchLatestOrders() {
      try {
        const response = await getLatestOrders()
        if (response && response.code === 200 && response.data) {
          this.latestOrders = response.data.map(order => {
            // 确保每个订单都有用户名
            return {
              ...order,
              username: order.username || '未知用户',
              totalAmount: order.totalAmount || 0,
              createTime: order.createdTime || '未知时间'
            }
          })
        } else {
          this.latestOrders = []
          console.error('获取最新订单数据格式异常:', response)
        }
      } catch (error) {
        console.error('获取最新订单失败:', error)
        this.latestOrders = []
      }
    },

    initCharts() {
      // 初始化销售趋势图
      this.salesChart = echarts.init(this.$refs.salesChart)
      this.salesChart.setOption({
        title: {
          text: '近7天销售趋势'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: [],
          type: 'line',
          smooth: true
        }]
      })

      // 初始化商品类别占比图
      this.categoryChart = echarts.init(this.$refs.categoryChart)
      this.categoryChart.setOption({
        title: {
          text: '商品类别销售占比'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [{
          name: '销售占比',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: true,
            position: 'outside'
          },
          data: []
        }]
      })
    },

    updateCharts(data) {
      // 更新销售趋势图数据
      if (this.salesChart) {
        this.salesChart.setOption({
          xAxis: {
            data: data.salesTrend.map(item => item.date)
          },
          series: [{
            data: data.salesTrend.map(item => item.amount)
          }]
        })
      }

      // 更新商品类别占比图数据
      if (this.categoryChart) {
        this.categoryChart.setOption({
          series: [{
            data: data.categoryDistribution
          }]
        })
      }
    },

    resizeCharts() {
      if (this.salesChart) {
        this.salesChart.resize()
      }
      if (this.categoryChart) {
        this.categoryChart.resize()
      }
    },

    getOrderStatusType(status) {
      const statusMap = {
        pending: 'warning',
        paid: 'success',
        shipped: 'primary',
        completed: 'success',
        cancelled: 'danger'
      }
      return statusMap[status] || 'info'
    },

    getOrderStatusText(status) {
      const statusMap = {
        pending: '待付款',
        paid: '已付款',
        shipped: '已发货',
        completed: '已完成',
        cancelled: '已取消'
      }
      return statusMap[status] || status
    },

    formatGrowthRate(rate) {
      if (rate === null || rate === undefined) return '0.00';
      return Number(rate).toFixed(2);
    },

    formatMoney(amount) {
      if (amount === null || amount === undefined) return '0.00';
      return Number(amount).toFixed(2);
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;

  .stat-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .title {
        font-size: 16px;
        color: #606266;
      }

      i {
        font-size: 24px;
        color: #409EFF;
      }
    }

    .card-body {
      .number {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 10px;
      }

      .growth {
        font-size: 14px;
        color: #909399;
        margin-top: 8px;
        
        &.up {
          color: #67C23A;
        }
        
        &.down {
          color: #F56C6C;
        }

        i {
          margin-right: 5px;
          &.el-icon-top {
            color: #67C23A;
          }
          &.el-icon-bottom {
            color: #F56C6C;
          }
        }
      }
    }
  }

  .chart-row {
    margin-top: 20px;
  }

  .chart-card {
    .chart {
      height: 300px;
    }
  }

  .latest-orders {
    margin-top: 20px;
  }
}
</style> 